package com.shop.controller;


import com.shop.entity.ProductType;
import com.shop.service.ProductTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author D
 * @since 2023-03-11 03:02:04
 */
@RestController
@RequestMapping("/productType")
public class ProductTypeController {
    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final int TYPELISTOVERTIMEOUT = 7;

    @RequestMapping("/getProductTypeList")
    public List<ProductType> getProductTypeList() {

        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        List<ProductType> productTypeList = (List<ProductType>) opsForValue.get("productTypeList");
        if (productTypeList == null) {
            productTypeList = productTypeService.list();
            opsForValue.set("productTypeList", productTypeList, TYPELISTOVERTIMEOUT, TimeUnit.DAYS);
        }
        return productTypeList;
    }

    @RequestMapping("/getType")
    public ProductType getType(Integer typeId) {
        String productTypeId = "productTypeId:" + typeId;
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        ProductType productType = (ProductType) opsForValue.get(productTypeId);
        if (productType == null) {
            productType = productTypeService.getById(typeId);
            opsForValue.set(productTypeId, productType, TYPELISTOVERTIMEOUT, TimeUnit.DAYS);
        }
        return productType;
    }
}

